#define _CRT_SECURE_NO_WARNINGS
using namespace std;
#include"VectorEmu.h"
/**
 * 类外实现模板函数注意：
 * 1. 需要使用 template<typename T>
 * 2. 要添加类名并且带模板参数 MyVector<T>::
*/

//Expand()
template<typename T>
void MyVector<T>:: Expand() {
    unsigned int sz_num = (this->length) * sizeof(T);
    T* newdata = new T[2 * length];
    (this->length) *= 2;
    //void memcpy(void* dest, const void* souarce, size_t num);
    memcpy(newdata, this->data, sz_num);
    delete this->data;
    this->data = newdata;
    int sz = this->length;
    cout << "Expand complete. " << "current capacity:"<< this->length << endl;
}

//clear()
template<typename T>
void MyVector<T>::clear() {
    if (data==nullptr||empty()==true) {
        printf("Vector is now empty!\n");
        return;
    }
    delete data;
    data = nullptr;
    this->current_pos = -1;
    this->length = 0;
}


//insert()
template <typename T>
void MyVector<T>::insert(int index,const T& d) {
    //索引合法性检查
    if (index<0 || index>(this->current_pos+1)) {
        printf("index: %d out of range\n", index);
        return;//存疑，如何返回
    }

    //容量不足时扩容
    if (this->length<=this->current_pos+2) {
        Expand();
        //unsigned int sz_num = (this->length)*sizeof(T);
        //T* newdata = new T[2 * length];
        //(this->length) *= 2;
        ////void memcpy(void* dest, const void* souarce, size_t num);
        //memcpy(newdata, this->data, sz_num);
        //delete this->data;
        //this->data = newdata;
        //cout << "Expand complete" << endl;
    }

    //一般情况 insert
    int end = this->current_pos + 1;
    while (end>=index)
    {
        this->data[end + 1] = this->data[end];//对于end+1，是否越界，尾插可以体现
        end--;
    }
    this->data[index] = d;
    (this->current_pos)++;
}

//remove()
template <typename T>
void MyVector<T>::remove(int index) {

    //索引合法性检查
    if (index<0 || index>current_pos) {
        printf("index: %d out of range\n", index);
        return;//存疑，如何返回
    }
    //一般情况
    int end = this->current_pos + 1;
    int cur = index;
    while (end>=cur)
    {
        this->data[cur] = this->data[cur + 1];
        cur++;
    }
    (this->current_pos)--;
}

//pushback
template <typename T>
void MyVector<T>::push_back(const T& d) {
    //判断是否需要扩容
    if (this->length<=this->current_pos+2) {//容量不足
        Expand();
    }
    //一般情况：
    this->data[this->current_pos + 1] = d;
    (this->current_pos)++;
}

//Popback()
template <typename T>
void MyVector<T>::pop_back() {
    //可以直接套用Remove
    // 
    //这里我们选择自己写：

    //边界检查
    if (empty()) {
        cout << "Pop fail ,Vector is no empty! " << endl;
        return;
    }
    cout << "Pop: " << this->data[this->current_pos] << endl;
    (this->current_pos)--;
}